<template>
  <!-- 设备统计模板 -->
  <!-- 右侧内容 -->

  <div>
    <gongyong ref="gongyong" :gongyongOption="gongyongOption">
      <!-- 顶部栏 -->
      <template #top-left>
        <div class="block">
          <span class="date-text">参数</span>
          <el-select v-model="paramValue" placeholder="请选择" size="mini" @change="changeParam">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <span class="date-text" style="margin-left:20px;">日期</span>
          <el-date-picker size="mini" v-model="dateValue" type="datetimerange" range-separator="→" value-format="yyyy-MM-dd HH:mm:ss" start-placeholder="开始时间" end-placeholder="结束时间" :clearable="false" @change="dateChange">
          </el-date-picker>
          <!-- <el-date-picker size="mini" v-model="dateValue" type="datetimerange" range-separator="→" start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker> -->
        </div>
      </template>

      <!-- 中间图表 -->
      <template #centre>
        <div ref="myChart" :style="{ width: '100%', height: '270px' }" v-loading="loading"></div>
      </template>

      <!-- 下边的Table组件 -->
      <template #bottom>
        <div class="derivedTbale">
          <div>实时数据</div>
          <!-- <div class="importX">
            <el-button icon="el-icon-download" type="success" plain @click="exportXlsx" size="mini" :disabled="disableds">导出Excel</el-button>
          </div> -->
        </div>
        <deviceTable :devTable="realTimeData" v-loading="loading" :tableStyle="tableStyle" :hYid="hYid" :reportDate="reportDate" :czFlag="czFlag"></deviceTable>
      </template>
    </gongyong>
  </div>
</template>

<script>
import gongyong from "../layout/gongyong.vue"; // 共用模板
import echarts from "echarts"; // 引入eahers
import deviceTable from "../components/deviceTable.vue";
// import derivedTbale from "../components/derivedTbale.vue"; //导出Excel

import {
  PostEquipstat, //设备统计列表
  PostEquipstatlistAll, //设备统计柱状图
  PostEquipstatExprotXls, //导出xlsx数据
} from "@/api/operationAnalysis/waterAnalysis";
import {
  searchflReportData,// 查询上报曲线
} from "@/api/schedule/base/flOverviewPipe/index";
export default {
  components: {
    gongyong,
    deviceTable
  },
  props: [
    "nodeData",
    "monitorPointId"
  ],
  data () {
    return {
      czFlag: true,
      options: [
        {
          label: '压力',
          value: '压力'
        },
        {
          label: '温度',
          value: '温度'
        },
        {
          label: '流量',
          value: '流量'
        },
        {
          label: '浊度',
          value: '浊度'
        },
        {
          label: '余氯',
          value: '余氯'
        },
        {
          label: 'PH',
          value: 'PH'
        },
        {
          label: '电池电压',
          value: '电池电压'
        },
        {
          label: '信号强度',
          value: '信号强度'
        },
      ],
      paramValue: '压力',
      gongyongOption: {
        top: true,
        center: true,
        bottom: true,
        rest: true, // 重置按钮
      }, // 共用组件配置---------
      // 导出Excel---------
      disableds: false,
      disabledImport: false,

      loading: false,
      dateValue: "", // 日期绑定
      suoS: {
        monitorPointId: "", // 监测点ID
        searchStartDate: "2022-01-01", // 日期绑定 开始时间
        searchEndDate: "", // 日期绑定 结束时间
      }, // 查询条件
      facilityData: [], // 设备统计列表
      facilityPillarData: [], // 设备统计柱状图
      Myecharts: {},
      // 数据列表的配置对象
      dataList: [
        {
          prop: "pumpsetName",
          label: "上报时间",
          id: 1,
        },
        {
          prop: "startDate",
          label: "压力(Mpa)",
          id: 2,
        },
        {
          prop: "endDate",
          label: "流量(m³/h)",
          id: 3,
        },
        // {
        //   prop: "runTimeDouble",
        //   label: `液位(m)`,
        //   id: 4,
        // },
        {
          prop: "runTimeDouble",
          label: `温度(℃)`,
          id: 4,
        },
        {
          prop: "runTimeDouble",
          label: `电池电压(V)`,
          id: 4,
        },
        {
          prop: "runTimeDouble",
          label: `信号强度`,
          id: 4,
        },
        {
          prop: "runTimeDouble",
          label: `开关阀`,
          id: 4,
        },
        {
          prop: "runTimeDouble",
          label: `倾斜角度(°)`,
          id: 4,
        },
      ],
      tableStyle: {
        TableHight: "330",
      }, // table 表格组件高度
      dateObj: {
        createDateStart: "",
        createDateEnd: "",
        monitorPointId: ""
      },
      reportDate: {
        reportDateStart: "",
        reportDateEnd: "",
      },
      hYid: "",
      realTimeData: ""
    };
  },
  watch: {
    nodeData: {
      handler (val) {
        this.suoS.monitorPointId = val.id;
        // console.log(this.monitorPointId);
      },
      deep: true,
    },
    monitorPointId: {
      handler (val) {
        console.log(val)
        this.dateObj.monitorPointId = val
        this.hYid = val
        this.handleLatestData(this.paramValue, this.dateObj)
      }
    }
  },
  created () { },
  mounted () {
    // this.suoS.monitorPointId = this.$parent.$parent.$parent.nodeData.id; // 拿到监测点ID用来发送请求，目的是一进来就可以看到数据
    let date = new Date();
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    if (month < 10) {
      month = "0" + month
    }
    let day = date.getDate()
    if (day < 10) {
      day = "0" + day
    }
    this.dateObj.createDateStart = year + "-" + month + "-" + day + " 09:00:00",
      this.dateObj.createDateEnd = year + "-" + month + "-" + day + " 10:59:59"
  },

  // 取出设备名称运行时长
  computed: {},
  methods: {
    //获取上报数据绘制曲线
    handleLatestData (val, obj) {
      // console.log(val,obj)
      // debugger;
      // let date = new Date();
      // let year = date.getFullYear()
      // let month = date.getMonth()
      // let day = date.getDate()
      // this.dateObj = {
      //   createEndDate: year + "-" + month + "-" + day + " 00:00:00",
      //   createStartDate: year + "-" + month + "-" + day + " 23:59:59"
      // }
      // let obj = obj
      searchflReportData(obj).then(response => {
        let data = response.data
        // console.log(data)
        // debugger;
        this.realTimeData = data
        let xData = []
        let y1Data = []
        let y2Data = []
        let yName
        if (val == "压力") {
          data.map(item => {
            xData.push(item.createDate)
            y1Data.push(item.houseInPressure)
            // y2Data.push(item.pressureLowLimit)
          })
          yName = "压力(MPa)"
        }
        if (val == "温度") {
          data.map(item => {
            xData.push(item.createDate)
            // y1Data.push(item.temperature)
          })
          yName = "温度(°C)"
        }
        if (val == "流量") {
          data.map(item => {
            xData.push(item.createDate)
            y1Data.push(item.houseOutflow)
          })
          yName = "流量(m³/h)"
        }
        if (val == "浊度") {
          data.map(item => {
            xData.push(item.createDate)
            y1Data.push(item.houseTurbidity)
          })
          yName = "浊度"
        }
        if (val == "余氯") {
          data.map(item => {
            xData.push(item.createDate)
            y1Data.push(item.houseChlorine)
          })
          yName = "余氯"
        }
        if (val == "PH") {
          data.map(item => {
            xData.push(item.createDate)
            y1Data.push(item.housePh)
          })
          yName = "PH"
        }
        this.drawLine(xData, y1Data, y2Data, yName);
      }).catch(error => {
      });
    },
    //切换参数
    changeParam (v) {
      this.paramValue = v
      this.handleLatestData(v, this.dateObj)
    },
    exprotXlsx: PostEquipstatExprotXls,
    newdata () {
      //获取当前时间
      var date = new Date();
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      if (month < 10) {
        undefined;
        month = "0" + month;
      }
      if (day < 10) {
        undefined;
        day == "0" + day;
      }
      this.suoS.searchEndDate = year += "-" + month + "-" + day;
    },

    // 发请求获取统计数据前判断
    getStatistics () {

    },

    // 发送请求后的判断
    senEndresult (res) {
      if (res.code !== 20000) {
        this.$message.error("查询失败");
        return;
      }
      if (res.data.length < 1) {
        // console.log(res.data);
        return this.$message.error("此时间阶段不存在");
      }
    },

    // 柱状图
    async sendPostEquipstatlistAll () {
      this.getStatistics();
      const res = await PostEquipstatlistAll(this.suoS);
      this.senEndresult(res);
      this.facilityPillarData = res.data;
      let defArray = res.data.map((item) => {
        return item.pumpsetName;
      });
      let defRun = res.data.map((item) => {
        return item.runTimeDouble;
      });
      // console.log(newDefArray);
      this.loading = false;
    },

    // 发数据统计列表
    async sendPostEquipstat () {
      this.getStatistics();

      const res = await PostEquipstat(this.suoS);
      this.senEndresult(res);

      this.facilityData = res.data;
      // console.log(res.data);
      this.$message.success("查询成功");
      this.loading = false;
    },

    // 日期选择
    dateChange (e) {
      console.log(e);
      if (e) {
        this.dateObj = {
          reportDateStart: e[0],
          reportDateEnd: e[1],
          monitorPointId: this.hYid
        }
        this.reportDate = {
          reportDateStart: e[0],
          reportDateEnd: e[1]
        }
      } else {
        let date = new Date();
        let year = date.getFullYear()
        let month = date.getMonth() + 1
        if (month < 10) {
          month = "0" + month
        }
        let day = date.getDate()
        if (day < 10) {
          day = "0" + day
        }
        this.dateObj.reportDateStart = year + "-" + month + "-" + day + " 00:00:00",
          this.dateObj.reportDateEnd = year + "-" + month + "-" + day + " 23:59:59",
          this.dateObj.monitorPointId = this.hYid
        this.reportDate = {
          reportDateStart: "",
          reportDateEnd: ""
        }
        if (this.czFlag == true) {
          this.czFlag = false
        } else {
          this.czFlag = true
        }
      }
      this.handleLatestData(this.paramValue, this.dateObj)
    },

    // 搜索按钮触发事件
    // async serchClick () {
    //   console.log(this.dateValue)
    //   this.dateObj = {
    //     reportDateStart: this.dateValue[0],
    //     reportDateEnd: this.dateValue[1]
    //   }
    //   this.reportDate = {
    //     reportDateStart: this.dateValue[0],
    //     reportDateEnd: this.dateValue[1]
    //   }
    //   this.handleLatestData(this.paramValue, this.dateObj)
    // },

    drawLine (xData, y1Data, y2Data, yName) {
      // 基于准备好的dom，初始化echarts实例
      let myChart = echarts.init(this.$refs.myChart);
      let ser
      if (y2Data.length >= 1) {
        ser = [
          {
            name: "当前值",
            data: y1Data,
            color: ["#EEAFAF"],
            type: 'line',
            smooth: true
          },
          {
            name: "压力低限",
            data: y2Data,
            color: ["#0B9AC3"],
            type: 'line',
            smooth: true
          }
        ]
      } else {
        ser = [
          {
            name: "当前值",
            data: y1Data,
            color: ["#EEAFAF"],
            type: 'line',
            smooth: true
          },
          {
            name: "",
            data: [],
            color: ["#0B9AC3"],
            type: 'line',
            smooth: true
          }
        ]
      }
      // 绘制图表
      let option = {
        xAxis: {
          type: "category",
          splitLine: {
            show: false,
          },
          data: xData,
          axisTick: {
            alignWithLabel: true,
          },
        },
        yAxis: {
          axisLine: { show: false },
          axisTick: { show: false },
          type: "value",
          name: yName,
          axisLable: {
            formatter: "{value}",
          }
        },
        grid: {
          x: 55,
          x2: 55,
          y: 28,
          y2: 35,
        },
        series: ser,
        tooltip: {
          trigger: "axis",
        },
        // legend: {
        //   x: "center", //可设定图例在左、右、居中
        //   y: "top", //可设定图例在上、下、居中
        //   padding: [20, 0, 0, 0],
        // },
      };
      myChart.setOption(option);
      window.addEventListener("resize", function () {
        console.log(123);
        myChart.resize();
      });
    },
    // 导出方法
    async exportXlsx () {
      this.disableds = true;
      console.log(123);

      try {
        const { exprotXlsx } = this.$parent;
        for (let item in this.suoS) {
          if (
            Array.isArray(this.suoS[item]) &&
            [
              "book",
              "hangbookCode",
              "bookName",
              "meterReadingManual",
              "name",
              "bookId",
            ].includes(item)
          ) {
            this.suoS[item] = this.suoS[item].join(",");
          }
        }
        const suoSs = this.suoS;
        let multipleSelections = this.multipleSelection;
        console.log(multipleSelections, 999);
        let ids = [];
        for (let i = 0; i < multipleSelections.length; i++) {
          const element = multipleSelections[i];
          ids.push(element.id);
        }

        let res = ids.length
          ? await exprotXlsx(ids, suoSs)
          : await exprotXlsx("ids", suoSs);
        console.log(res, "导出结果");
        let fileName = decodeURI(res["filename"].split("=")[1]);

        let blob = new Blob([res], {
          type: "application/vnd.ms-excel;charset=utf-8",
        });
        var downloadA = document.createElement("a");
        downloadA.download = fileName;
        downloadA.style.display = "none";
        downloadA.href = URL.createObjectURL(blob);
        document.body.appendChild(downloadA);
        downloadA.click();
        URL.revokeObjectURL(downloadA.href);
        document.body.removeChild(downloadA);
        // 提示
        this.$notify({
          title: "导出成功",
          message: fileName,
          type: "success",
        });
      } catch (error) {
        console.log(error);
        this.$notify.error({
          title: "错误",
          message: "下载失败！",
        });
      } finally {
        this.disableds = false;
      }
    },
    // 点击重置按钮
    // resetClick () {
    //   this.dateValue = "";
    //   this.dateObj = {
    //     reportDateStart: "",
    //     reportDateEnd: ""
    //   }
    //   if (this.czFlag == true) {
    //     this.czFlag = false
    //   } else {
    //     this.czFlag = true
    //   }
    //   this.handleLatestData(this.paramValue, this.dateObj)
    // },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-date-editor .el-range-separator {
  padding: 0px 0px;
}
.date-text {
  font-size: 14px;
}
.derivedTbale {
  display: flex;
  width: 100%;
  height: 37px;
  border-bottom: 1px solid #e4e4e4;
  position: relative;
}
.importX {
  position: absolute;
  top: 0px;
  right: 0px;
}
</style>
